const alert = msg =>{
  msg += "";
  wx.showModal({
    content: msg,
    showCancel: false,
    success: function (res) {}
  });
};
const toast = msg=>{
  msg += "";
  wx.showToast({
    title: msg,
    icon: 'none',
    duration: 2000
  });
};
const loading = msg =>{
  msg = (msg)?msg+"":'';
  wx.showLoading({
    title: msg,
  });
};
//格式化数字
const formatNumber = function (s, n, sci) {
  if (s == "undefined" || s == "null" || s == "NULL" || s == "") { s = 0; }
  else if (isNaN(parseFloat(s))) { return s; }
  n = n > 0 && n <= 20 ? n : 2;
  s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
  var l = s.split(".")[0].split("").reverse(),
    r = s.split(".")[1];
  var t = "";
  for (var i = 0; i < l.length; i++) {
    t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length && sci === true ? "," : "");
  }
  return t.split("").reverse().join("") + "." + r;
};
const formatTime = function(date) {
  if (arguments.length == 0) {
    date = new Date();
  }
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return [year, month, day].map(fixZero).join('-') + ' ' + [hour, minute, second].map(fixZero).join(':');
};
const formatDate = function (date) {
  if(arguments.length==0){
    date = new Date();
  }
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return [year, month, day].map(fixZero).join('-');
};

const fixZero = n => {
  n = n.toString();
  return n[1] ? n : '0' + n;
}
const request = function (json) {
  var ts = (new Date()).getTime();
  if(!json.success){
    json.success = function(){};
  }
  if (!json.error) {
    json.error = function (code,msg) {
      alert("["+code+"]"+msg);
    };
  }
  if (!json.complete) {
    json.complete = function () { };
  }
  if(!json.url){
    alert("Request Url Is Empty");
    console.log("request[" + ts + "]:URL is empty");
    return;
  }
  if(json.loading){
    if (typeof (json.loading) == "function") {
      loading(json.loading);
    } else {
      loading(json.loading + '');
    }
  }else if(json.loading===false || json.loading===null){
  }else{
    loading('数据加载中');
  }
  if(!json.returnType){
    json.returnType = "mywy";
  }
  if(!json.dataType){
    json.dataType = "json";
  }
  if (!json.responseType){
    json.responseType = "text";
  }
  console.log("request["+ts+"]:url=" +json.url);
  console.log("request[" + ts +"]:data="+JSON.stringify(json.params));
  var task = wx.request({
    url: json.url,
    data: json.params,
    dataType : json.dataType,
    responseType: json.responseType,
    header: {'content-type': 'application/json'},
    success: function (res) {
      if(json.returnType=="mywy"){
        console.log("request[" + ts +"]:success:returnType=mywy");
        var re = res.data;
        if (res.statusCode != 200) {
          console.log("util:request:success:res=网络异常");
          json.error(res.statusCode, '网络异常');
        } else {
          console.log("request[" + ts +"]:success:res="+re.code+":"+re.msg);
          if (re.code == 0) {
            json.success(re.data);
          } else{
            console.log("request failed on "+json.url);
            json.error(
              ival(re.code,'-1'), 
              val(re.msg,"未知错误")
            );
          }
        } 
      }else{
        console.log("request[" + ts +"]:success:res=" + res.code + ":" + res.msg);
        json.success(res);
      }
    },
    fail: function (res) {
      console.log("request[" + ts +"]:success:fail=" + res.errMsg);
      json.error("FAIL", res.errMsg);
    },
    complete: function () {
      wx.hideLoading();
      json.complete();
    }
  });
  return task;
};
const val = function(v,def){
  if(arguments.length==1){def='';}
  if (typeof(v)=="undefined" || v=='' ||  v==null || v=="undefined"){
    return def;
  }
  return v;
};
const jval = function (v, def) {
  if (arguments.length == 1) { def = {}; }
  if (v!=null && typeof (v) == "object") {
    return v;
  }
  return def;
};
const ival = function(v,def){
  if (arguments.length == 1) { def = 0; }
  v = parseInt(v);
  v = isNaN(v)?def:v;
  return v;
};
const fval = function(v,def,tails){
  if (arguments.length == 1) { def = 0; }
  v = parseFloat(v);
  v = isNaN(v) ? def : v;
  if(tails>0){
    return formatNumber(v,tails);
  }else{
    return v;
  }
};
const LocalStorageUsing = function (k, v) {
  if (arguments.length == 1) {
    try {
      v = wx.getStorageSync(k);
      console.log("my:L:get:"+k+":"+v);
      return v;
    } catch (e) {
      console.log("my:L:"+e);
      alert("my:L:"+e.message);
    }
  } else if (arguments.length = 2) {
    try {
      console.log("my:L:set:" + k + ":" + v);
      wx.setStorageSync(k, v);
    } catch (e) {
      console.log("my:L:" + e);
      alert("my:L:" + e.message);
    }
  }
};
const log = function(msg,point){
  var logs = wx.getStorageSync('logs') || []
  var t = formatTime(new Date());
  var s = '[' + t + ']';
  if(point){
    s += '['+point+']';
  }
  s += msg;
  logs.unshift(s);
  wx.setStorageSync('logs', logs);
};
const logClean = function(){
  wx.setStorageSync('logs',[]);
};
const msg = function(page,json){
  console.log("my.msg:json:" + JSON.stringify(json));
  var route = page.route;
  console.log("route=" + route);
  if (route) {
    var parr = route.split('/');
    var path = '';
    for (var i = 2; i < parr.length; i++) {
      path += '../';
    }
    path += "msg/msg";
  } else {
    path = "../msg/msg";
  }
  console.log("path=" + path);
  LocalStorageUsing("msg_content", json.content);
  LocalStorageUsing("msg_result_type", json.resultType);
  wx.redirectTo({
    url: path,
  });
};
const error = function(page,json){
  console.log("my.error:json:" + JSON.stringify(json));
  var route = page.route;
  console.log("route="+route);
  if(route){
    var parr = route.split('/');
    var path = '';
    for (var i = 2; i < parr.length; i++) {
      path += '../';
    }
    path += "error/error";
  }else{
    path = "../error/error";
  }
  console.log("path=" + path);
  LocalStorageUsing("error_message", {
    code: ival(json.code, 100),
    msg: val(json.msg, 'Unknown'),
    track: val(json.track, ''),
    mode: ival(json.mode),
    back : val(json.back),//错误页面回退的地址
  });
  console.log("json.mode="+json.mode);
  if(json.mode==1){//按异常来处理
    wx.redirectTo({
      url: path,
    });
  }else{
    wx.navigateTo({
      url: path,
    });
  }
};
const concat = function(arr1,arr2){
  if (!Array.isArray(arr1)){
    console.log("arr1 type="+typeof(arr1));
    arr1 = [];
  }
  if (!Array.isArray(arr2) || arr2.length<1){
    console.log("arr2 type=" + typeof (arr2));
    return arr1;
  }
  for(var i=0;i<arr2.length;i++){
    arr1.push(arr2[i]);
  }
  return arr1;
};
const cut = function(str,size,tail){
  tail = val(tail);
  str = val(str);
  if(str.length>size){
    str = str.substr(0,size)+tail;
  }
  return str;
};
const kminstance = function(lat1,lng1,lat2,lng2){
  var inst = getFlatternDistance(lat1, lng1, lat2, lng2);
  if(lat1<=0 || lng1<=0 || lat2<=0 || lng2<=0){
    return "";
  }
  if(inst<=100){
    return "<100米";
  }else  if (inst > 100 && inst<1000) {
    return parseInt(inst)+'米';
  }else if(inst>=100000){
    return ">100公里";
  }else{
    return formatNumber(inst/1000,1)+"公里";
  }
};
const getFlatternDistance = function(lat1, lng1, lat2, lng2,unit) {
  lat1 = fval(lat1);
  lat2 = fval(lat2);
  lng1 = fval(lng1);
  lng2 = fval(lng2);

  var EARTH_RADIUS = 6378137.0;    //单位M
  var PI = Math.PI;

  var getRad = function(d) {
    return d * PI / 180.0;
  };
  var f = getRad((lat1 + lat2) / 2);
  var g = getRad((lat1 - lat2) / 2);
  var l = getRad((lng1 - lng2) / 2);

  var sg = Math.sin(g);
  var sl = Math.sin(l);
  var sf = Math.sin(f);

  var s, c, w, r, d, h1, h2;
  var a = EARTH_RADIUS;
  var fl = 1 / 298.257;

  sg = sg * sg;
  sl = sl * sl;
  sf = sf * sf;

  s = sg * (1 - sl) + (1 - sf) * sl;
  c = (1 - sg) * (1 - sl) + sf * sl;

  w = Math.atan(Math.sqrt(s / c));
  r = Math.sqrt(s * c) / w;
  d = 2 * w * a;
  h1 = (3 * r - 1) / 2 / c;
  h2 = (3 * r + 1) / 2 / s;

  var inst = d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
  return (unit == 'km') ? formatNumber(inst / 1000, 1):ival(inst);
};
const appendOptions = function(path,options) {
  var p = [];
  for (var key in options) {
    p.push(key + '=' + options[key]);
  }
  if (p.length > 0) {
    path = path + "?" + p.join('&');
  }
  console.log("my:appendOptions:path=" + path);
  return path;
};
const random = function(min,max){
  return Math.floor(Math.random() * (max - min + 1) + min);
};
module.exports = {
  cut:cut,
  random: random,
  concat: concat,
  formatTime: formatTime,
  formatDate: formatDate,
  formatNumber: formatNumber,
  alert:alert,
  toast: toast,
  loading: loading,
  request: request,
  L: LocalStorageUsing,
  log:log,
  logClean : logClean,
  val : val,
  jval:jval,
  ival : ival,
  fval : fval,
  formatNumber: formatNumber,
  error : error,
  msg: msg,
  getFlatternDistance: getFlatternDistance,
  kminstance: kminstance,
  appendOptions: appendOptions,
}